using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.PersonAssociationTemplates
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="PersonAssociationTemplate"/> instances.
    /// </summary>
    public class PersonAssociationTemplateCommandHandler :
        ICommandHandler<EnterPersonAssociationTemplate>,
        ICommandHandler<ChangePersonAssociationTemplate>,
        ICommandHandler<DeletePersonAssociationTemplate>
    {
        private readonly IRepository _repository;

        public PersonAssociationTemplateCommandHandler(IRepository repository)
        {
            _repository = repository;
        }

        public void Handle(EnterPersonAssociationTemplate command)
        {
            PersonAssociationTemplate personAssociationTemplate = new PersonAssociationTemplate(command.PersonAssociationTemplateId, command.AssociationName);
            SavePersonAssociationTemplate(personAssociationTemplate);
        }

        public void Handle(ChangePersonAssociationTemplate command)
        {
            PersonAssociationTemplate personAssociationTemplate = _repository.GetById<PersonAssociationTemplate>(command.PersonAssociationTemplateId, command.Version);
            personAssociationTemplate.Change(command.AssociationName);
            SavePersonAssociationTemplate(personAssociationTemplate);
        }

        public void Handle(DeletePersonAssociationTemplate command)
        {
            PersonAssociationTemplate personAssociationTemplate = _repository.GetById<PersonAssociationTemplate>(command.PersonAssociationTemplateId, command.Version);
            personAssociationTemplate.Delete();
            SavePersonAssociationTemplate(personAssociationTemplate);
        }

        private void SavePersonAssociationTemplate(PersonAssociationTemplate personAssociationTemplate)
        {
            _repository.Save(personAssociationTemplate, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}